package com.ch.base.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet { 
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		String fileUri = request.getRequestURI(); 
		String contextPath = request.getContextPath(); 
		fileUri = fileUri.substring(contextPath.length());

		try{
			InputStream is = getClass().getResourceAsStream(fileUri);
			if(is!=null){
				int i = is.available(); //得到文件大小
				byte data[] = new byte[i];
				is.read(data); //讀數據
				is.close();
				response.setContentType("image/*"); //設置返回的文件類型
				OutputStream toClient=response.getOutputStream(); //得到向客戶端輸出二進制數據的對象
				toClient.write(data); //輸出數據
				toClient.close();
			}
		}catch(IOException e){ //錯誤處理
			PrintWriter toClient = response.getWriter(); //得到向客戶端輸出文本的對象
			response.setContentType("text/html;charset=utf-8");
			toClient.write("ImageServlet.doGet(request, response): Can't open the image!");
			toClient.close();
		}
	}
}
